package developer.zyk.global.upload.upload.handlers;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import developer.zyk.global.upload.FileUtil;
import developer.zyk.global.config.PlatFormProperties;
import developer.zyk.global.config.UploadProperties;
import developer.zyk.global.upload.dao.entity.ChatObjectRepositoryDO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.UUID;

/**
 * @author zhangyongkang
 * @time 2025/5/14 11:08
 * @description: <a href="https://cloud.tencent.com/document/product/436/7751?from=console_document_search">
 * 腾讯OCS对象存储接口文档
 * </a>
 */
@Component("tencentUploadService")
public class TencentUploadService implements UploadService {
    @Resource
    private FileUtil fileUtil;
    @Resource
    private UploadProperties uploadProperties;
    @Resource
    private PlatFormProperties platFormProperties;


    public UploadHandlerResult singleUploadStream(DoUploadRequest doUploadRequest, InputStream inputStream) {
        COSClient client = getClient();
        try {
            // 指定文件将要存放的存储桶
            String bucketName = uploadProperties.getTenxunConfig().getDefaultBucketName();
            // 指定文件上传到 COS 上的路径，即对象键。例如对象键为 folder/picture.jpg，则表示将文件 picture.jpg 上传到 folder 路径下
            String key = doUploadRequest.getPath();
            ObjectMetadata objectMetadata = new ObjectMetadata();
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, inputStream, objectMetadata);
            PutObjectResult putObjectResult = client.putObject(putObjectRequest);
            URL objectUrl = client.getObjectUrl(bucketName, key);

            UploadHandlerResult uploadHandlerResult = new UploadHandlerResult();
            uploadHandlerResult.setUrl(objectUrl.getProtocol() + "://" + objectUrl.getHost() + objectUrl.getPath());
            uploadHandlerResult.setHost(objectUrl.getHost());
            uploadHandlerResult.setPath(objectUrl.getPath());
            uploadHandlerResult.setPlatFormId(key);
            uploadHandlerResult.setBucketName(bucketName);
            return uploadHandlerResult;
        } finally {
            client.shutdown();
        }
    }

    @Override
    public File download(Long fileId) {
        COSClient client = getClient();
        ChatObjectRepositoryDO fileInfo = fileUtil.getFileByFileId(fileId);
        GetObjectRequest getObjectRequest = new GetObjectRequest(fileInfo.getBucketName(), fileInfo.getPlatformOutId());
        File localFile = new File(getLocalFileUrl(UUID.randomUUID().toString() + fileInfo.getFileName()));
        client.getObject(getObjectRequest, localFile);
        client.shutdown();
        return localFile;
    }

    private String getLocalFileUrl(String fileName) {
        String dirPath = System.getProperty("user.dir") + File.separator + "temp" + File.separator;
        File file = new File(dirPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        return dirPath + fileName;
    }

    private COSClient getClient() {
        // 1 初始化用户身份信息（secretId, secretKey）
        /*
          SECRETID 和 SECRETKEY 请登录访问管理控制台 https://console.cloud.tencent.com/cam/capi 进行查看和管理
         */
        PlatFormProperties.TengXun tengXun = platFormProperties.getTengXun();
        String secretId = tengXun.getSecretId();//用户的 SecretId，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
        String secretKey = tengXun.getSecretKey();//用户的 SecretKey，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // 2 设置 bucket 的地域, COS 地域的简称请参见 https://cloud.tencent.com/document/product/436/6224
        /* clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。*/
        Region region = new Region(uploadProperties.getTenxunConfig().getRegion());
        ClientConfig clientConfig = new ClientConfig(region);
        /*这里建议设置使用 https 协议 从 5.6.54 版本开始，默认使用了 https*/
        clientConfig.setHttpProtocol(HttpProtocol.https);
        // 3 生成 cos 客户端。
        return new COSClient(cred, clientConfig);
    }


}
